// cloudfunctions/getMessages.js
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        const {
            fromUserId,
            toUserId,
            pageNum = 1,
            pageSize = 20,
            goodsId = null
        } = event

        // 生成会话ID: buyerId_sellerId_goodsId
        const conversationId = fromUserId < toUserId ?
            `${fromUserId}_${toUserId}_${goodsId}` :
            `${toUserId}_${fromUserId}_${goodsId}`;

        // 构建查询条件
        // 构建查询条件
        const queryCondition = db.command.or([{
                fromUserId,
                toUserId,
                goodsId
            },
            {
                fromUserId: toUserId,
                toUserId: fromUserId,
                goodsId
            }
        ]);
        console.log('消息列表查询条件', queryCondition);
        // 查询消息列表
        const messages = await db.collection('messages')
            .where(queryCondition)
            .orderBy('createTime', 'desc')
            .skip((pageNum - 1) * pageSize)
            .limit(pageSize)
            .get()

        // 使用事务更新消息状态和会话未读计数
        const transaction = await db.startTransaction();
        try {
            // 1. 标记消息为已读
            await transaction.collection('messages')
                .where({
                    toUserId: fromUserId,
                    fromUserId: toUserId,
                    goodsId,
                    isRead: false
                })
                .update({
                    data: {
                        isRead: true
                    }
                });

            // 2. 查询会话文档（根据 conversationId 字段）
            const conversationQuery = await transaction.collection('conversations')
                .where({
                    conversationId
                })
                .limit(1)
                .get();
            console.log('会话文档', conversationQuery);
            if (conversationQuery.data && conversationQuery.data.length > 0) {
                const conversationDoc = conversationQuery.data[0];

                // 3. 更新会话未读计数
                await transaction.collection('conversations')
                    .doc(conversationDoc._id) // 使用数据库自增ID
                    .update({
                        data: {
                            unreadCount: 0,
                            lastMessage: messages.data[0] || null,
                            updateTime: db.serverDate()
                        }
                    });
            }

            // 4. 更新用户消息状态（可选，根据您的业务需求）
            await transaction.collection('user_message_status')
                .where({
                    userId: fromUserId,
                    conversationId
                })
                .update({
                    data: {
                        unreadCount: 0
                    }
                });

            // 提交事务
            await transaction.commit();

        } catch (error) {
            // 回滚事务
            await transaction.rollback();
            throw error;
        }

        return {
            success: true,
            messages: messages.data.reverse(),
            hasMore: messages.data.length === pageSize
        }

    } catch (error) {
        console.error('获取消息列表失败:', error);
        return {
            success: false,
            message: error.message || '获取消息列表失败'
        };
    }
}